package com.hylanda.pb.dao;

import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Repository;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hylanda.pb.entity.PBLocal;
import com.hylanda.pb.model.PBLocalQo;
import com.hylanda.pb.service.common.ConstantHelper;
import com.hylanda.util.http.OkHttpUtils;

/** 
 * @author zhangy
 * @E-mail:blackoon88@gmail.com 
 * @qq:846579287
 * @version created at：2018年3月14日 下午2:50:40 
 * note
 */
@Repository
public class PBLocalDao {
	@Autowired
	private OkHttpUtils okHttpUtils;
	@Value("${powerbiProxySever.host}")
	public String host;
	@Value("${powerbiProxySever.port}")
	public int port;
	public PBLocal findEntity(Class<PBLocal> class1, Long id) {
		return null;
	}

	public PBLocal save(PBLocal pBLocal) {
		return null;
	}

	public int update(PBLocal pBLocal) {
		return 0;
	}

	public void delete(Class<PBLocal> class1, Long id) {
		
	}

	public Page<PBLocal> findPage(PBLocalQo qo ) {
		String url = "http://"+this.host+":"+this.port+ConstantHelper.folder_get;
		String response = okHttpUtils.sendPowerbiHttp(url);
		if (response.startsWith(ConstantHelper.ERROR_HEAD)) {
			return null;
		}
		JSONArray reports =null;
		try {
			JSONObject json = JSONObject.parseObject(response);
			reports= json.getJSONArray("value");
		} catch (Exception e) {
		}
		if(reports==null)
			return null;
		
		Pageable pageable = new PageRequest(qo.getPage(), qo.getSize(), Sort.Direction.DESC, "id");
//		int minRowNumber = qo.getPage() * qo.getSize();
		List<PBLocal> results = new ArrayList<PBLocal>();
		for (int i = 0; i < reports.size(); i++) {
			PBLocal pbLocal=new PBLocal();
			JSONObject report = reports.getJSONObject(i);
			String name= report.getString("Name");
			if(name.length()<=1)
				continue;
			pbLocal.setName(report.getString("Name"));
			pbLocal.setId(report.getString("Id"));
			pbLocal.setType(report.getString("Type"));
			results.add(pbLocal);
		}
		int total = results.size();
		return new PageImpl<PBLocal>(results, pageable, total);
	}
//	public boolean uploadCatalogItem(Part part, String parentName) {
//		CredentialsProvider credentialsProvider = httpClientUtils.getCredentialsProvider();
//		HttpClientContext httpClientContext = httpClientUtils.getHttpClientContext(credentialsProvider);
//		try {
//			FileInfo fileInfo = new FileInfo();
//			fileInfo.setName(part.getSubmittedFileName());
//			fileInfo.setExtension(part.getSubmittedFileName().substring(part.getSubmittedFileName().lastIndexOf(".") + 1));
//			fileInfo.setSize(part.getSize());
//			// File file = new File(part.getSubmittedFileName());
//			// FileUtils.copyInputStreamToFile(part.getInputStream(), file);
//			// String content=IOUtils.toString(part.getInputStream(), "utf-8");
//			String content = Base64Utils.encode(part.getInputStream());
//			System.out.println("getContentType"+part.getContentType());
//			System.out.println(new String(Base64Utils.decode(content.getBytes()),"gbk"));
//			System.out.println(new String(Base64Utils.decode(content.getBytes()),"iso-8859-1"));
//			IOUtils.closeQuietly(part.getInputStream());
//			fileInfo.setContent(content);
//			fileInfo.setContentType(part.getContentType());
//			
//			String uri = UrlConstantHelper.uploadCatalogItem_post;
//			Map<String, String> headParams = new HashMap<String, String>();
//			headParams.put("Content-Type", "application/json;charset=UTF-8");
//			Item item = new Item();
//			item.setContent(fileInfo.getContent());
//			item.setContentType("");
//			item.setName(fileInfo.getName());
//			item.setPath(parentName == null ? "/" + fileInfo.getName()
//					: parentName + "/" + fileInfo.getName());
//			JSONObject joItem = JSON.parseObject(JSON.toJSONString(item));
//			addDataType(joItem, fileInfo);
//			StringEntity entitys = new StringEntity(JSON.toJSONString(joItem));
//			
//			httpClientUtils.httpPost(this.hostname, this.port, this.scheme, uri, headParams,httpClientContext, entitys);
//
//			String fileName = fileInfo.getName().substring(0,
//					fileInfo.getName().lastIndexOf("."));
//			uri = UrlConstantHelper.getCatalogItemInfo_get.replaceAll("name",
//					(parentName == null ? fileName
//							: (parentName + "/" + fileName)));
//			String response = httpClientUtils.httpGet(this.hostname, this.port, this.scheme,
//					uri, headParams, httpClientContext);
//			BigCatalogItem bigCatalogItem = JSON.parseObject(response,
//					BigCatalogItem.class);
//
//			DataSource dataSource = bigCatalogItem.getDataSources()[0];
//			dataSource.setDataSourceType("SQL");
//			dataSource.setIsConnectionStringOverridden(true);
//			dataSource.setCredentialRetrieval("store");
//			DataModelDataSource dataModelDataSource = dataSource
//					.getDataModelDataSource();
//			dataModelDataSource.setUsername("adm");
//			dataModelDataSource.setSecret("Hailiang888");
//			dataModelDataSource.setAuthType("UsernamePassword");
//			CredentialsInServer credentialsInServer = null;
//			if (dataSource.getCredentialsInServer() == null) {
//				credentialsInServer = new CredentialsInServer();
//			} else {
//				credentialsInServer = dataSource.getCredentialsInServer();
//			}
//
//			credentialsInServer.setUserName("adm");
//			credentialsInServer.setPassword("Hailiang888");
//			credentialsInServer.setUseAsWindowsCredentials(true);
//			credentialsInServer.setImpersonateAuthenticatedUser(false);
//			DataSource[] dataSources = new DataSource[] { dataSource };
//
//			uri = UrlConstantHelper.updateDataSource_patch.replaceAll(
//					"bigItem.Id", bigCatalogItem.getId());
//			entitys = new StringEntity(JSON.toJSONString(dataSources), "UTF-8");
//			httpClientUtils.httpPatch(this.hostname, this.port, this.scheme, uri, headParams,
//					httpClientContext, entitys);
//		} catch (Exception e) {
//			return false;
//		}
//		return true;
//
//	}
//	
//	public ApiResponse createFolder(String parentName) {
//		//校验是否存在
//		Map<String, String> headParams = new HashMap<String, String>();
//		headParams.put("Content-Type", "application/json;charset=UTF-8");
//		CredentialsProvider credentialsProvider = httpClientUtils.getCredentialsProvider();
//		HttpClientContext httpClientContext = httpClientUtils.getHttpClientContext(credentialsProvider);
//		String uri=UrlConstantHelper.folder_get;
//		String response=null;
//		try {
//			response=httpClientUtils.httpGet(this.hostname, this.port,this.scheme, uri, headParams, httpClientContext);
//			//不存在创建
//			JSONObject joo=JSON.parseObject(response);
//			JSONArray array=joo.getJSONArray("value");
//			if(array!=null&&array.size()>0){
//				boolean iscontinue=false;
//				for(int i=0;i<array.size();i++){
//					if(parentName.equals(array.getJSONObject(i).getString("Name"))
//							&&"Folder".equals(array.getJSONObject(i).getString("Type"))){
//						iscontinue=true;
//						break;
//					}
//				}
//				if(!iscontinue){
//					Folder folder=new Folder();
//					folder.setId(UUID.randomUUID().toString());
//					folder.setName(parentName);
//					folder.setPath("/"+parentName);
//					folder.setType("Folder");
//					JSONObject jo=JSON.parseObject(JSON.toJSONString(folder));
//					jo.put("@odata.context", joo.getString("@odata.context")+"/$entity");//"http://localhost/reports/api/v2.0/$metadata#CatalogItems/$entity"
//					jo.put("@odata.type", "#Model.Folder");
//					StringEntity entitys = new StringEntity(JSON.toJSONString(jo));
//					response=httpClientUtils.httpPost(this.hostname, this.port,this.scheme, uri, headParams, httpClientContext, entitys);
//				}
//			}
//		} catch (Exception e) {
//			e.printStackTrace();
//			return new ApiResponse(response);
//		}
//		return new ApiResponse();
//	}
//
//	private void addDataType(JSONObject item, FileInfo fileInfo) {
//		switch (fileInfo.getExtension().toLowerCase()) {
//		case "rdl":
//			item.put("@odata.type", "#Model.Report");
//			break;
//		case "rsd":
//			item.put("@odata.type", "#Model.DataSet");
//			break;
//		case "rds":
//			item.put("@odata.type", "#Model.Resource");
//			item.put("ContentType", "text/xml");
//			break;
//		case "rsc":
//			item.put("@odata.type", "#Model.Component");
//			break;
//		case "rsmobile":
//			item.put("@odata.type", "#Model.MobileReport");
//			break;
//		case "pbix":
//			item.put("@odata.type", "#Model.PowerBIReport");
//			break;
//		case "xls":
//		case "xlsb":
//		case "xlsm":
//		case "xlsx":
//		case "csv":
//			item.put("@odata.type", "#Model.ExcelWorkbook");
//			break;
//		default:
//			item.put("@odata.type", "#Model.Resource");
//			break;
//		}
//	}
//
//	public ApiResponse patchDataSource(String path, ConnectionString json) {
//		String response =null;
//		try {
//			Map<String, String> headParams = new HashMap<String, String>();
//			headParams.put("Content-Type", "application/json;charset=UTF-8");
//			CredentialsProvider credentialsProvider = httpClientUtils.getCredentialsProvider();
//			HttpClientContext httpClientContext = httpClientUtils.getHttpClientContext(credentialsProvider);
//			String uri = UrlConstantHelper.getCatalogItemInfo_get.replaceAll("name",path);
//			response = httpClientUtils.httpGet(this.hostname, this.port, this.scheme,uri, headParams, httpClientContext);
//			BigCatalogItem bigCatalogItem = JSON.parseObject(response,BigCatalogItem.class);
//
//			DataSource dataSource = bigCatalogItem.getDataSources()[0];
//			dataSource.setDataSourceType("SQL");
//			dataSource.setIsConnectionStringOverridden(true);
//			dataSource.setCredentialRetrieval("store");
//			
//			StringBuilder connectionString =new StringBuilder();
//			connectionString.append("data source=").append("HYP\\MSSQLSERVER2").append(";")
//			.append("initial catalog=").append("xzdata").append(";")
//			.append("user id=").append("sa").append(";")
//			.append("password=").append("hylanda").append(";")
//			.append("persist security info=").append("False").append(";")
//			.append("encrypt=").append("True").append(";")
//			.append("trustservercertificate=").append("False");
//			
//			
//			
//			dataSource.setConnectionString(connectionString.toString());
//			
//			DataModelDataSource dataModelDataSource = dataSource.getDataModelDataSource();
//			dataModelDataSource.setUsername("sa");
//			dataModelDataSource.setSecret("hylanda");
//			dataModelDataSource.setAuthType("UsernamePassword");
//			CredentialsInServer credentialsInServer = null;
//			if (dataSource.getCredentialsInServer() == null) {
//				credentialsInServer = new CredentialsInServer();
//			} else {
//				credentialsInServer = dataSource.getCredentialsInServer();
//			}
//
//			credentialsInServer.setUserName("sa");
//			credentialsInServer.setPassword("hylanda");
//			credentialsInServer.setUseAsWindowsCredentials(true);
//			credentialsInServer.setImpersonateAuthenticatedUser(false);
//			dataSource.setCredentialsInServer(credentialsInServer);
//			DataSource[] dataSources = new DataSource[] { dataSource };
//			System.out.println(JSON.toJSONString(dataSources));
//			uri = UrlConstantHelper.updateDataSource_patch.replaceAll("bigItem.Id", bigCatalogItem.getId());
//			StringEntity entitys = new StringEntity(JSON.toJSONString(dataSources), "UTF-8");
//			response=httpClientUtils.httpPatch(this.hostname, this.port, this.scheme, uri, headParams,httpClientContext, entitys);
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
//		
//		return new ApiResponse(response);
//	}

//	public ApiResponse queryDataSource(String path) {
//		String response =null;
//		try {
//			Map<String, String> headParams = new HashMap<String, String>();
//			headParams.put("Content-Type", "application/json;charset=UTF-8");
//			CredentialsProvider credentialsProvider = httpClientUtils.getCredentialsProvider();
//			HttpClientContext httpClientContext = httpClientUtils.getHttpClientContext(credentialsProvider);
//			String uri = UrlConstantHelper.getCatalogItemInfo_get.replaceAll("name",path);
//			response = httpClientUtils.httpGet(this.hostname, this.port, this.scheme,uri, headParams, httpClientContext);
//		} catch (IOException e) {
//			e.printStackTrace();
//		}
//		return new ApiResponse(response);
//	}
	
}
